// 导入数据库模块
const db = require("../db/index.js");

const nodemailer = require("nodemailer");

// 导入加密模块
// const bcryptjs = require("bcryptjs");

// 导入token生成包
const jwt = require("jsonwebtoken");

// 导入全局的配置文件
const config = require("../config");

// 用户注册
exports.userRegister = (req, res) => {
  let userInfo = req.body;
  console.log(userInfo.is_admin);
  let selectSql = `select * from users where email = ?`;
  let getCodeSql = `select code from userscode where email = ?`;
  let insertSql = `insert into users(user_id,password,email,is_admin)values(?,?,?,?)`;

  db.query(selectSql, userInfo.email, (err, results) => {
    if (err) {
      throw new Error("NotFound");
    }
    if (results.length >= 1) {
      res.send({
        code: 200,
        message: "该用户已注册，请登录",
      });
    } else {
      db.query(getCodeSql, userInfo.email, (err, results) => {
        if (err) {
          throw new Error("NotFound");
        }
        let userCode = results[0].code;
        console.log(userInfo.code, userCode);
        if (Number(userInfo.code) !== userCode) {
          res.send({
            code: 400,
            message: "验证码错误",
          });
        } else {
          console.log(userInfo);
          db.query(
            insertSql,
            [userInfo.account, userInfo.password, userInfo.email,userInfo.is_admin],
            (err, result) => {
              if (err) {
                throw new Error("NotFound");
              }
              res.send({
                code: 200,
                message: "用户注册成功",
              });
            }
          );
        }
      });
    }
  });
};

// 获取注册验证码
exports.getCode = (req, res) => {
  let email = req.query.email;

  // 生成随机验证码
  let code = Math.floor(Math.random() * 900000) + 100000;
  let selectSql = `select * from userscode where email = ?`;
  let insertSql = `insert into userscode(email,code)values(?,?)`;
  let updateSql = `update userscode set code = ? where email = ?`;
  // 建立SMTP连接
  let transporter = nodemailer.createTransport({
    host: "smtp.qq.com",
    secureConnection: true,
    port: 465,
    auth: {
      user: "2218903219@qq.com",
      pass: "kchfwvobteshdijf",
    },
  });
  let options = {
    from: "2218903219@qq.com",
    to: `2218903219@qq.com,${email}`,
    subject: "校园失物招领系统注册",
    html: `<div style="width:600px;margin:30px auto">
                    <h1 style="text-align:center;">欢迎注册校园失物招领系统账户</h1>
                    <p style="font-size:24px">此次的验证码如下：</p>
                    <strong style="font-size:20px;display:block;text-align:center;color:red;">${code}</strong>
                    <p>验证码15分钟有效，请及时输入</p><i style="color:#00bfff">此邮件为系统自动发送，请勿回复！若您没有进行注册请忽略。</i> 
                    <p style="text-align:right">--程序员Grand.</p>
                </div>`,
  };
  transporter.sendMail(options, (err, msg) => {
    if (err) {
      console.log(err);
    } else {
      res.send(msg);
      transporter.close();
    }
  });
  db.query(selectSql, email, (err, result) => {
    if (err) {
      throw new Error("NotFound");
    }
    if (result.length >= 1) {
      db.query(updateSql, [code, email], (err, results) => {
        if (err || results.affectedRows !== 1) {
          throw new Error("NotFound");
        } else {
          res.send({
            data: code,
            message: "获取验证码成功",
            code: 200,
          });
        }
      });
    } else {
      db.query(insertSql, [email, code], (err, results) => {
        if (err || results.affectedRows !== 1) {
          throw new Error("NotFound");
        } else {
          res.send({
            data: code,
            message: "获取验证码成功",
            code: 200,
          });
        }
      });
    }
  });
};

// 用户登录
exports.userLogin = (req, res) => {
  let userInfo = req.body;
  if (userInfo.account === "" || userInfo.password === "") {
    return res.send({
      code: 400,
      message: "账号或密码为空",
    });
  }
  let sqlStr = `select * from users where user_id = ? and password = ?`;
  const sql = `update users set login_time = ? where user_id = ?`;
  db.query(sqlStr, [userInfo.account, userInfo.password], (err, result) => {
    if (err) {
      throw Error("NotFound");
    }
    if (
      result.length !== 1 ||
      result[0].user_id !== userInfo.account ||
      result[0].PASSWORD !== userInfo.password
    ) {
      return res.send({
        code: 400,
        message: "账号密码错误",
      });
    }
    const user = { ...result[0] };
    const tokenStr = jwt.sign({user_id:user.user_id}, config.jwtSecretKey, {
      expiresIn: config.expiresIn,
    });
    db.query(sql, [userInfo.login_time, userInfo.account], (err, results) => {
      if (err) {
        throw Error("Server Error");
      }
      res.send({
        code: 200,
        message: "登录成功",
        data: {
          token: tokenStr,
        },
      });
    });
  });
};

// 获取用户信息
exports.getUserInfo = (req, res) => {
  const sql = `select * from users where user_id = ?`;
  db.query(sql, req.query.user_id, (err, result) => {
    if (err) {
      throw Error("Server Error");
    }
    res.send({
      code: 200,
      data: result[0],
    });
  });
};

// 更新用户信息
exports.updateUserInfo = (req, res) => {
  const userInfo = req.body;
  const sql = `update users set sex = ? ,head = ? ,money_code = ? ,signature = ? where user_id = ?`;
  db.query(
    sql,
    [
      userInfo.sex,
      userInfo.head,
      userInfo.money_code,
      userInfo.signature,
      userInfo.user_id,
    ],
    (err, result) => {
      if (err) {
        throw Error("server");
      }
      res.send({
        code: 200,
        message: "更新成功",
      });
    }
  );
};

// 增加反馈
exports.feedback = (req, res) => {
  const sql = `insert into feedback(user_id,topic,advise,TIME)values(?,?,?,?)`;
  db.query(
    sql,
    [req.body.user_id, req.body.topic, req.body.advise, req.body.TIME],
    (err, result) => {
      if (err) {
        throw Error("Server Error");
      }
      res.send({
        code: 200,
        message: "提交成功",
      });
    }
  );
};

// 修改反馈
exports.updateFeedback = (req, res) => {
  const sql = `update feedback set topic = ? , advise = ?, TIME = ? where id = ?`;
  db.query(
    sql,
    [req.body.topic, req.body.advise, req.body.TIME, req.body.id],
    (err, result) => {
      if (err) {
        throw Error("Server Error");
      }
      res.send({
        code: 200,
        message: "更新成功",
      });
    }
  );
};

// 删除反馈
exports.deleteFeedback = (req, res) => {
  const sql = `delete from feedback where id = ?`;
  db.query(
    sql,
    req.query.id,
    (err, result) => {
      if (err) {
        throw Error("Server Error");
      }
      res.send({
        code: 200,
        message: "删除成功",
      });
    }
  );
};


// 获取全部反馈（分页）
exports.getFeedback = (req, res) => {
  const pageNo = req.query.pageNo
  const pageSize = Number(req.query.pageSize)
  const startIndex = (pageNo - 1) * pageSize
  const sql = `select * from feedback`
  db.query(sql, (err, result) => {
    if (err) {
      throw Error("Server Error");
    }
    const data = result.slice(startIndex, startIndex + pageSize)
    // console.log(data);
    res.send({
      code: 200,
      data: {
        dataLength: result.length,
        result,
        data
      }
    })
  })
}



// 获取所有用户
exports.getAllUser = (req, res) => {
  const sql = `select * from users`
  db.query(sql, (err, result) => {
    if (err) {
      throw Error("Server Error");
    }
    res.send({
      code: 200,
      data: result
    })
  })
}
